package com.datx.wallet.config;

import com.datx.wallet.base.BaseResponse;
import com.datx.wallet.base.BaseResponseCode;
import com.datx.wallet.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang.exception.ExceptionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;

/**
 * Interceptor Created with IntelliJ IDEA.
 * User: liulinhui
 * Date: 2018/9/4
 * Time: 19:35
 * Description: Interceptor
 */
@Aspect
@Component
@Slf4j
public class Interceptor {

    @Resource
    private WalletProperties walletProperties;

    @Pointcut("@annotation(com.datx.wallet.annotation.HttpApi)")
    public void allMethod() {
    }

    //环绕
    @Around("allMethod()")
    public Object aroundExec(ProceedingJoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        BaseResponse result;
        try {
            result = (BaseResponse) joinPoint.proceed();
            BaseResponse finalResult = result;
            //拦截器统一拦截coinType,coinName,asset字段，判断是否支持此货币
            Map<String, String[]> parameterMap = request.getParameterMap();
            parameterMap.keySet().forEach(key -> {
                //校验是否支持该货币
                if (Arrays.asList("coinType", "coinName", "asset").contains(key)) {
                    if (null == walletProperties.getCoinFactory().get(parameterMap.get(key)[0])) {
                        finalResult.setCode(BaseResponseCode.ERROR.getCode());
                        finalResult.setData(null);
                        finalResult.setMessage("不支持" + key + "这种货币");
                    }
                }
            });
            result = finalResult;
        } catch (Throwable e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            if (e instanceof BaseException) {
                BaseException baseException = (BaseException) e;
                result = new BaseResponse(baseException.getBaseResponseCode(), e);
            } else result = new BaseResponse(e);
        }
        return result;
    }
}
